<?php

namespace app\api\controller;

use app\admin\model\CarModel;
use app\api\model\UserCoupon;
use app\common\controller\Api;
use app\api\model\Coupon as couponModel;

class Order extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];


    //预估价格
    public function estimatePrice(){
        $start = input('start');
        $end = input('end');
        $cid = input('cid');//选择车型ID
        $data = $this->kmPrice($start,$end,$cid);
        $this->ajaxSuccess($data);
    }

    //计算历程对应价格
    public function kmPrice($start,$end,$cid){
        $start = input('start');
        $end = input('end');
        $cid = input('cid');//选择车型ID
        $carModel = new CarModel();
        $key = '8882f439beba7fe4c082d62f1fe81803';
        $url = 'https://restapi.amap.com/v3/distance?origins='.$start.'&destination='.$end.'&output=JSON&key='.$key;
        $json = file_get_contents($url);
        $result = json_decode($json,true);
        if($result['status'] != 1){
            $this->ajaxError('请检查请求参数');
        }
        $distance = $result['results'][0]['distance'];
        $distance = round($distance/1000,2);//两点之间的公里数
        $carInfo = $carModel->where(['id'=>$cid])->find();
        $price = json_decode($carInfo['price'],true);
        $unitPrice = 0;//一公里单价
        $lastOne = array_pop($price);
        if($distance > $lastOne['kilometre']){//判断是否大于最大设置公里数
            $unitPrice = $carInfo['end_price'];
        }else{
            array_push($price, $lastOne);
            foreach ($price as $key=>$row){
                if($distance > $row['kilometre']){
                    $unitPrice = $price[$key+1]['price'];
                }
            }
        }
        $estimatePrice = round($unitPrice*$distance,2);
        if($estimatePrice < $carInfo['start_price']){
            $estimatePrice = $carInfo['start_price'];
        }
        $data = [
            'price'=>$estimatePrice,
            'distance'=>$distance,
            'unit_price'=>$unitPrice,
        ];
        return $data;
    }
    //订单提交
    public function downOrder(){
        $data['start'] = input('start');//起点经纬度
        $data['end'] = input('end');//终点经纬度
        $data['car_id'] = input('cid');//车型ID
        $data['start_text'] = input('start_text');//起点地址
        $data['end_text'] = input('end_text');//终点地址
        $data['photos'] = input('photos');//上传图片地址
        $data['mark'] = input('mark');//订单备注
        $data['coupon_id'] = input('coupon_id');//所选优惠券ID
        $data['order_num'] = orderNum();//生成订单号
        $data['user_id'] = $this->uid;
        $data['weight'] = input('weight');//货物重量
        $data['use_time'] = input('use_time')?:time();//用车时间
        $data['send_name'] = input('send_name');//发货人姓名
        $data['send_mobile'] = input('send_mobile');//发货人手机
        $data['receive_name'] = input('receive_name');//收货人姓名
        $data['receive_mobile'] = input('receive_mobile');//收货人手机
        $info = $this->kmPrice($data['start'],$data['end'],$data['car_id']);//计算里程  价格
        $data['kilometre'] = $info['distance'];
        $data['km_price'] = $info['price'];
        $data['createtime'] = time();
        $data['updatetime'] = time();
        $userCoupon = new UserCoupon();
        $couponInfo = $userCoupon
            ->alias('a')
            ->field('a.id,b.cut_price,b.use_price,a.status')
            ->join('coupon b','a.cid=b.id')
            ->where([
                'a.id'=>$data['coupon_id'],
            ])
            ->find();
        if($couponInfo){
            if($couponInfo['status'] != 1){
                $this->ajaxError('该优惠券已使用');
            }
            $data['coupon_price'] = $couponInfo['cut_price'];//优惠券抵扣金额
            $couponInfo->status = 2;
            $couponInfo->save();
        }
        $msg['id'] = db('order')->insertGetId($data);
        $this->ajaxSuccess($msg);
    }
    //订单详情
    public function orderInfo(){
        $order = db('order')
        ->alias('a')
        ->join('driver b','a.driver_id = b.id','left')
        ->where('a.id',input('id'))
        ->field("a.*,FROM_UNIXTIME(a.use_time,'%Y-%m-%d %H:%i:%s') as use_time,FROM_UNIXTIME(a.createtime,'%Y-%m-%d %H:%i:%s') as createtime,b.name as driver_name,b.mobile as driver_mobile")
        ->find();
        $this->ajaxSuccess($order);
    }
    //订单取消
    public function orderCancel(){
        $id = input('id');
        $order = db('order')->where('id',$id)->find();
        if($order['status'] != 1){
            $this->ajaxError('该订单不可取消');
        }
        db('order')->where('id',$id)->update([
            'status'=>5,
        ]);
        $this->ajaxSuccess();
    }
    //订单修改接单时间
    public function changeTime(){
        $id = input('id');
        $time = input('time');
        $order = db('order')->where('id',$id)->find();
        if($order['status'] != 1){
            $this->ajaxError('该订单不可修改时间');
        }
        db('order')->where('id',$id)->update([
            'use_time'=>$time,
        ]);
        $this->ajaxSuccess();
    }

    //订单列表
    public function orderList(){
        $uid = $this->uid;
        $status = input('status');
        $num = 10;
        $page = input('page');
        if ($status==0){
            $where = [
                    'o.user_id'=> $uid,
                ];
        }else{
            $where = [
                    'o.user_id'=> $uid,
                    'o.status'=> $status
                ];
        }
        $list = db('order')->alias('o')->field('o.id,order_num,d.name,d.mobile,start_text,end_text,o.status')
                ->join('driver d','o.driver_id=d.id','left')
                ->where($where)
                ->select();
        $count = db('order')->alias('o')->field('order_num')
            ->join('driver d','o.driver_id=d.id','left')
            ->where($where)
            ->page($page)
            ->limit($num)
            ->count();
        $allpage = ceil($count/$num);
        $data=[
            'list' => $list,
            'page' => $page,
            'allpage' => $allpage
        ];
        $this->ajaxSuccess($data);
    }
    
    
    
}
